package cn.edu.glut.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonBackReference;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * 
 * @author Caizhfy
 * @email caizhfy@163.com
 * @createTime 2017年12月9日
 * @description 题目 加锁机制：选课时插入中间表记录同时更新该表number字段， 两部操作放入事务中，出现并发即可回滚
 *
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(exclude = "selections")
@Accessors(chain = true)
@Entity
@Table
public class Subject implements Serializable {

	private static final long serialVersionUID = 1451928124417199842L;
	@Id
	@GeneratedValue(generator = "uuid")
	@GenericGenerator(name = "uuid", strategy = "uuid")
	private String id;
	private String title;
	private String description;
	@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date releaseTime; // 发布时间
	private Integer offer; // 供选人数
	private Integer number; // 题目供选剩余量
	@Version
	private Long version; // 乐观锁字段
	@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
	@JoinColumn(name = "teacher_id")
	private Teacher teacher;
	@ManyToOne
	@JoinColumn(name = "major_id")
	private Major major;
	@JsonBackReference
	@OneToMany(mappedBy = "subject")
	private List<Selection> selections;

	public Subject(String id) {
		super();
		this.id = id;
	}

	//只开放三个字段修改，别的一律不开放
	public Subject updateData(Subject s) {
		if (!StringUtils.isEmpty(s.getTitle()))
			this.title = s.getTitle();
		if (!StringUtils.isEmpty(s.getDescription()))
			this.description = s.getDescription();
		if(s.getMajor()!=null && !StringUtils.isEmpty(s.getMajor().getId()))
			this.major = s.getMajor();
		return this;
	}

}
